# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, RequestContext
from puzzleGame.forms import UploadImageForm
from puzzle.settings import MEDIA_ROOT, MEDIA_URL
import Image, os, random, shutil, string

newImages = []; imagesUrlWithEmpty=[]; imagesUrlWithEmptyResort=[];

def randstring(n):
    a = string.ascii_letters + string.digits
    return ''.join([random.choice(a) for i in range(n)])

def handle_uploaded_file(source):
    fileinst = MEDIA_ROOT + '/' + source.name
    with open(fileinst, 'wb+') as destination:
        for chunk in source.chunks():
            destination.write(chunk)
    return fileinst  

def upload_file(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST, request.FILES)
        if form.is_valid():
            fileinst = handle_uploaded_file(request.FILES['image'])
            return HttpResponseRedirect('/result/?fileinst=' + fileinst + '&nameFolder='+ request.FILES['image'].name[:-4])
    else:
        form = UploadImageForm()
    return render_to_response('fileUploader.html', {'form': form}, context_instance=RequestContext(request))

def fileReview(request):
    specific=""
    fileinst = request.GET['fileinst']
    folderName = request.GET['nameFolder']
    if (not os.path.exists(MEDIA_ROOT + '/' + folderName)):
        os.makedirs(MEDIA_ROOT + '/' + folderName)
    else:
        shutil.rmtree(MEDIA_ROOT + '/' + folderName)
        os.makedirs(MEDIA_ROOT + '/' + folderName)
    im = Image.open(fileinst)
    if(im.size[0]<im.size[1]):
        im = im.resize((300,400))
        cropVertical = 3; cropHorizontal = 4
        specific="vertical"
    else: 
        if(im.size[0]>im.size[1]):
            im = im.resize((400,300))
            cropVertical = 4; cropHorizontal = 3
            specific="horizontal"
        else:
            im =  im.resize((400,400)) 
            cropVertical = cropHorizontal = 4  
            specific="square"      
    newImages = []; tempHoriz = [] 
    slideh = 0
    for i in range(cropHorizontal):
        slidev = 0; tempVert = []
        tempHoriz.append(im.crop((0,slideh,im.size[0],(im.size[1]/cropHorizontal)+slideh)))  
        slideh += im.size[1]/cropHorizontal
        for j in range(cropVertical):
            tempVert.append(tempHoriz[i].crop((slidev,0,(tempHoriz[i].size[0]/cropVertical)+slidev,tempHoriz[i].size[1])))
            slidev += tempHoriz[i].size[0]/cropVertical             
        newImages.append(tempVert)             
    imagesUrl = []
    for item in newImages:
        for innerItem in item:
            ident = randstring(3)
            fileLocation = MEDIA_ROOT + '/' + folderName +'/' + folderName + ident + '.png'
            imagesUrl.append(MEDIA_URL + folderName +'/' + folderName + ident + '.png')
            innerItem.save(fileLocation)
    spaceh = cropVertical 
    spacev = cropHorizontal 
    
    imagesUrlWithEmptyResort = imagesUrlWithEmpty =  imagesUrl[:-1] 
    random.shuffle(imagesUrlWithEmptyResort)  
    
    return render_to_response('resultFile.html', {'images' : imagesUrlWithEmptyResort,  'specific' : specific, 'spaceh' : spaceh, 'spacev' : spacev },  context_instance=RequestContext(request))
